﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Collections.Specialized;
using System.IO;
using System.IO.Compression;

namespace Scatter
{
    public class Helper
    {
        public static bool CheckSessionTimeout(string currentCookie, string returnedCookie)
        {
            bool isTimeout = false;
            string returnedWosid = Helper.GetCookie(returnedCookie, new List<string>() { "wosid" });
            if (string.IsNullOrEmpty(returnedWosid) == false)
            {
                string currentWosid = Helper.GetCookie(currentCookie, new List<string>() { "wosid" });
                if (returnedWosid != currentWosid)
                {
                    isTimeout = true;
                }
            }
            return isTimeout;
        }

        private static string GetResponseContent(HttpWebResponse response)
        {
            Stream responseStream = response.GetResponseStream();
            StreamReader streamRead = null;
            if (response.ContentEncoding.ToLower() == "gzip")
            {
                streamRead = new StreamReader(new GZipStream(responseStream, CompressionMode.Decompress));
            }
            else
            {
                streamRead = new StreamReader(responseStream);
            }

            return streamRead.ReadToEnd();
        }

        public static string GetCookie(string cookieString, List<string> cookieNames)
        {
            int index;
            int length;
            List<string> cookieList = new List<string>();
            foreach (var item in cookieNames)
            {
                index = cookieString.IndexOf(item);
                if (index == -1)
                {
                    continue;
                }
                length = cookieString.IndexOf(';', index) - index;
                string cookie = cookieString.Substring(index, length);
                cookieList.Add(cookie);
            }
            return string.Join("; ", cookieList);
        }

        public static ResponseContext GetResponse(RequestContext context)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;

            try
            {
                request = WebRequest.Create(context.RequestUrl) as HttpWebRequest;
                request.Timeout = ConfigHelper.RequestTimeout;
                request.AllowAutoRedirect = context.AllowAutoRedirect;
                request.Method = context.Method;
                request.Accept = context.Accept;
                foreach (var item in context.Headers)
                {
                    request.Headers.Add(item.Key, item.Value);
                }
                if (context.Method == "POST")
                {
                    if (context.PostData != null)
                    {
                        request.ContentType = context.ContentType;

                        byte[] bytes = Encoding.UTF8.GetBytes(context.PostData);
                        request.ContentLength = bytes.Length;

                        Stream requestStream = request.GetRequestStream();
                        requestStream.Write(bytes, 0, bytes.Length);
                        requestStream.Close();
                    }
                    else
                    {
                        request.ContentLength = 0;
                    }
                }

                response = request.GetResponse() as HttpWebResponse;
                string responseContent = GetResponseContent(response);
                return new ResponseContext(response.StatusCode, response.Headers, responseContent);
            }
            finally
            {
                if (request != null)
                {
                    request.Abort();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
        }
    }

    public class RequestContext
    {
        public RequestContext()
        {
            Method = "GET";
            AllowAutoRedirect = false;
            Accept = "*/*";
            Headers = new Dictionary<string, string>();
        }

        public string RequestUrl { get; set; }
        public string Method { get; set; }
        public string Accept { get; set; }
        public string ContentType { get; set; }
        public string PostData { get; set; }
        public bool AllowAutoRedirect { get; set; }
        public Dictionary<string, string> Headers { get; private set; }
    }

    public class ResponseContext
    {
        public ResponseContext(HttpStatusCode statusCode, WebHeaderCollection headers, string content)
        {
            this.StatusCode = statusCode;
            this.Headers = headers;
            this.Content = content;
        }

        public HttpStatusCode StatusCode { get; private set; }
        public WebHeaderCollection Headers { get; private set; }
        public string Content { get; private set; }
    }
}
